<template>
  <div class="mark">
    <div class="left">
      <el-select v-model="currentSubjectName" :loading="selectLoading" placeholder="学科选择"
        style="min-width: 200px; margin-bottom: 10px" @change="change">
        <el-option v-for="(item, index) in subjectList" :key="index" :label="item.subjectName" :value="item" />
      </el-select>

      <el-tree ref="treeRef" :data="courseData" :expand-on-click-node="false" :highlight-current="true" :props="props"
        class="menu-tree" default-expand-all draggable node-key="id" @node-click="handleNodeClick" :loading="loading">
        <template #default="{ node, data }">
          <span class="custom-tree-node" style="min-width: 160px">
            <template v-if="!isEditing || editingNodeId !== data.id">
              {{ node.label }}
            </template>

            <template v-else>
              <el-input v-model="editingNodeLabel" @blur="cancelEdit(data)" @keyup.enter="updateNodeLabel(data)"
                ref="refInput" style="width: 60%; height: 20px"></el-input>
            </template>

            <span style="float: right">
              <a :style="{ marginRight: '0.5rem' }" @click="append(data)">
                <el-icon :style="{ color: '#0000FF' }">
                  <Plus />
                </el-icon>
              </a>

              <a :style="{ marginRight: '0.5rem' }" @click="remove(node, data)" v-if="data.id">
                <el-icon :style="{ color: '#DA3434' }">
                  <Delete />
                </el-icon>
              </a>
              <a :style="{ marginRight: '0.5rem' }" @click="edit(node, data)" v-if="data.id">
                <el-icon :style="{ color: '#0000FF' }">
                  <Edit />
                </el-icon>
              </a>
            </span>
          </span>
        </template>
      </el-tree>

      <!-- 删除 -->
      <el-dialog v-model="dialogVisible" title="确认删除" width="500">
        <span>删除后不可恢复，确定要删除吗？</span>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="deleteById"> 确定 </el-button>
          </div>
        </template>
      </el-dialog>

    </div>

    <div class="right">
      <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
        <el-tab-pane label="课程" name="课程">
          <!-- <Markdown :data="nodeData" /> -->
          <div id="vditor"></div>
        </el-tab-pane>
        <el-tab-pane label="作业" name="作业">
          <HomeworkList v-if="activeName=='作业'"  :data="nodeData"/>
        </el-tab-pane>
      </el-tabs>
    </div>


  </div>
</template>

<script setup>
import { nextTick, onMounted, onUpdated, ref, watch } from "vue"
import axios from "@/axios/index.js"
import { ElMessage } from "element-plus"
import { reactive } from "@vue/reactivity"
// import Markdown from "./Markdown.vue"
import HomeworkList from "./homeworkList.vue"
import Vditor from 'vditor'// 1.1 引入Vditor 构造函数
import 'vditor/dist/index.css'// 1.2 引入样式


// 2. 获取DOM引用
const vditor = ref()
const treeRef = ref(null)

let loading = ref(true)
let selectLoading = ref(true)

//课程数据
let courseData = reactive([])
//删除dialog控制
const dialogVisible = ref(false)
//当前要删除的课程id
let deleteId = ref()
//默认展示
const activeName = ref("课程")
//输入框自动聚焦
const refInput = ref()

//学科对象
let subjectList = reactive([])
//当前学科id
let currentSubjectId = ref(1)
let currentSubjectName = ref("")
//添加课件
let addForm = reactive({
  pid: "",
  courseName: "",
  order: "",
  subjectId: "",
  status: 1,
  courseTag: "",
  courseContent: "",
})

const props = {
  label: "courseName",
  children: "children",
}

/** 树节点id */
let id = 1000
/** 单击节点的数据 */
const nodeData = ref({})
/** 节点是否修改 */
const isEditing = ref(false)
/** 保存正在编辑的节点ID */
const editingNodeId = ref(null)
/** 临时存储编辑中的节点名称 */
const editingNodeLabel = ref("")

onMounted(() => {

    vditor.value = new Vditor('vditor', {
    width: '100%',
    height: '100%',
    blur: () => {
      axios.put(
        "api/v1/admin/course/courseContent",
        {
          id: nodeData.value.id,
          courseContent: vditor.value.getValue(),
        },
        {
          headers: {
            "Content-Type": "application/json",
          },
        }
      ).then((res) => {
        // ElMessage({
        //   message: res.data.message,
        //   type: "success",
        //   duration: 1000
        // })
      })
    },
  })
})

watch(loading, (newValue, oldValue) => {
  nextTick(() => {
    const tree = treeRef.value
    if (tree) {
      // 获取第一个节点（假设你想点击的是 id 为 1 的节点）
      const node = tree.getNode(3)
      if (node) {
        // 设置当前节点并手动触发点击事件
        tree.setCurrentKey(3)
        // 如果你需要确保点击事件处理函数被调用，也可以手动调用它
        handleNodeClick(node.data)
      }
    }
  })
})
/** 点击修改树节点 */
const edit = (node, data) => {
  isEditing.value = true
  editingNodeId.value = data.id
  editingNodeLabel.value = data.courseName

  nextTick(() => {
    refInput.value.focus()
  })
}

let homeworkList = ref(null)
/** 点击树节点 */

const handleNodeClick = (data) => {
  nodeData.value = data
  setTimeout(()=>{
    vditor.value.setValue(data.courseContent);
  },150)
  // vditor.value.setValue(data.courseContent)
  if (activeName.value === '作业') {
    if (homeworkList.value) {
      // 直接调用子组件的方法
      homeworkList.value.loadTableData();
    }
  }
}

/** 添加树节点 */
const append = (data) => {
  const newChild = { id: id, courseName: "", children: [] }
  if (!data.children) {
    data.children = []
  }
  data.children.push(newChild)

  //打开新建的文件编辑模式
  isEditing.value = true
  editingNodeId.value = id
  editingNodeLabel.value = ""
  nextTick(() => {
    refInput.value.focus()
  })

  addForm.pid = data.id
  addForm.order = 25
  addForm.subjectId = currentSubjectId.value
  addForm.courseTag = data.courseTag
}

/** 点击删除树节点 */
const remove = (node, data) => {
  dialogVisible.value = true
  deleteId.value = data.id
}

/** 进行删除*/
const deleteById = () => {
  axios
    .delete("api/v1/admin/course", {
      params: {
        courseId: deleteId.value,
      },
    })
    .then((res) => {
      dialogVisible.value = false
      getCoursetList()
    })
}

/** 更新节点名称 */
const updateNodeLabel = (data) => {
  if (data.id != 1000) {
    if (data.courseName != editingNodeLabel.value) {
      if (editingNodeId.value === data.id) {
        data.courseName = editingNodeLabel.value
        isEditing.value = false
        editingNodeId.value = null
        axios
          .put("api/v1/admin/course", null, {
            params: {
              courseId: data.id,
              courseName: editingNodeLabel.value,
            },
          })
          .then((res) => {
            getCoursetList()
          })
      }
    } else {
      isEditing.value = false
    }
  } else {
    addForm.courseName = editingNodeLabel.value
    axios
      .post("api/v1/admin/course", addForm, {
        headers: {
          "Content-Type": "application/json",
        },
      })
      .then((res) => {
        getCoursetList()
      })
  }
}

/** 取消节点编辑 */
const cancelEdit = (data) => {
  //如果取消编辑时id==1000 并且 绑定的变量为空 删除
  if (data.id == 1000 && editingNodeLabel.value == '') {
    loading.value = true
    deleteArr(courseData)
    loading.value = false
    console.log("为空");
  }else{
    updateNodeLabel(data)
  }
  isEditing.value = false
  editingNodeId.value = null
}

/** 递归删除未命名课件 */
function deleteArr(arr) {
  arr.forEach((item, index) => {
    if (item.id == 1000) {
      arr.splice(index, 1)
      courseData = [...courseData]
    } else if (item.children && Array.isArray(item.children)) {
      deleteArr(item.children)
    }
  })
}

/** 获取课程列表*/
function getCoursetList() {
  loading.value = true
  axios
    .get("api/v1/admin/course", {
      params: {
        subjectId: currentSubjectId.value,
      },
    })
    .then((res) => {
      loading.value = false
        courseData = [{ courseName: currentSubjectName.value, children: [] }]
      courseData[0].children = res.data.data
    })
}

/** 获取学科集合*/
function getSubjectList() {
  selectLoading.value = true
  axios
    .get("/api/v1/admin/subject", {
      params: { total: 0, currentPage: 1, pageSize: 5 },
    })
    .then((res) => {
      selectLoading.value = false
      subjectList = res.data.data
      currentSubjectName.value = subjectList[0].subjectName

      getCoursetList()
    })
}

getSubjectList()


/** 切换学科时的回调*/
function change(value) {
  currentSubjectId.value = value.id
  currentSubjectName.value = value.subjectName
  getCoursetList()
}
const handleClick = (event) => {
  activeName.value = event.props.name
}
</script>

<style scoped lang="less">
.mark {
  display: flex;
  height: calc(100vh - 150px);
}

.left {
  min-width: 300px;
  padding: 20px;
  border-right: 1px solid #bbbbbb;
  box-sizing: border-box;
  background-color: #fff;
  overflow-y: scroll;
}

.left::-webkit-scrollbar {
  width: 6px;
  background-color: transparent;
}

.finished {
  color: #d3d3d3;
}

::v-deep .el-tabs__nav-scroll {
  margin-left: 20px;
}

.unfinished {
  color: #606266;
}

.right {
  width: 1300px;

  .demo-tabs {
    width: 100%;
    height: 100%;

    .el-tab-pane {
      width: 100%;
      height: 100%;
    }
  }
}

.custom-tree-node {
  width: 300px;
}

div::-webkit-scrollbar-thumb {
  background: #40a0ff49;
  border-radius: 10px;
}

.el-tree{
  min-width: 200px;
  max-width: 300px;
}
</style>